/*  
 * @(#) LogFilter.java Create on 2013-7-22 下午03:21:01   
 *   
 * Copyright 2013 by xl.   
 */

package com.doeis.core.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.doeis.common.Constant;
import com.doeis.manage.bean.User;
import com.doeis.tools.ExceptionHelper;
import com.doeis.tools.StringHelper;

/**
 * 
 * @author xieyan
 * @date 2013-7-22
 */
@WebFilter(urlPatterns = { "/*" })
public class LogFilter implements Filter {

	protected Logger logger = Logger.getLogger(LogFilter.class);

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		// 将ServletRequest对象转换HttpServletRequest
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		try {
			String ip = StringHelper.getRequestIp(httpRequest);
			StringBuffer param = new StringBuffer("");
			String url = httpRequest.getRequestURI().toString();
			if (url.indexOf("/images") == 0 || url.indexOf("/js") == 0 // 脚本
					|| url.indexOf("/static/") != -1 // 样式
					|| url.indexOf("/index.jsp") == 0 )// 跳转页面
			{
				filterChain.doFilter(request, response);
				return;
			}
			@SuppressWarnings("rawtypes")
			Enumeration params = request.getParameterNames();
			if (params != null) {
				while (params.hasMoreElements()) {
					String key = (String) params.nextElement();
					if (key.indexOf("struts") != -1 || key.indexOf("_page") != -1 || key.indexOf("_search") != -1) { // 是struts或页数或查询条件的不记录
						continue;
					}

					String value = request.getParameter(key);
					if (StringHelper.isNotNull(value)) { // 值不为空的
						param.append(key + "==" + value + ",");
					}
				}
			}
			User user = (User) httpRequest.getSession().getAttribute(Constant.SYSTEM_CURRENT_USER);
			if (user != null) {
				String userRealName = user.getUsername();
				Integer userId = user.getId();
				String paramString = "";
				if (param != null) {
					paramString = param.toString();
				}
				logger.info("userId: " + userId + " | userRealName: " + userRealName + " | userIP:" + ip + " | url: " + url + " | param: "
						+ paramString.toString().replaceAll(",$", ""));
			}

			filterChain.doFilter(request, response);
		} catch (Exception ex) {
			logger.error("日志过滤器出错！！！" + ExceptionHelper.getStackTrace(ex));
			filterChain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
